﻿using Microsoft.SqlServer.Management.Smo;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AppManager
{
    public partial class FrmAppObjects : Form
    {
        public string SelectedObjectType { get; set; }

        public FrmAppObjects(string objectType)
        {
            InitializeComponent();
            SelectedObjectType = objectType;
            LoadObjects();
        }

        private void LoadObjects()
        {
            using (CRMDataContext dataContext = new CRMDataContext())
            {
                var result = from obj in dataContext.AppObjects
                             where obj.ObjectType == SelectedObjectType
                             select new { obj.Name , obj.ModuleID, obj.ObjectType, obj.LinkTable };
                GridObjects.AutoGenerateColumns = false;
                GridObjects.DataSource = result;
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (SelectedObjectType == "TABLE")
            {
                FrmNewTable frmtable = new FrmNewTable();
                frmtable.Show();
            }
            else if (SelectedObjectType == "LIST")
            {
                FrmNewList frm = new FrmNewList();
                frm.Show();
            }
            else if (SelectedObjectType == "CARD")
            {
                FrmNewCard frm = new FrmNewCard();
                frm.Show();
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadObjects();
        }

        private void GridObjects_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            string name = e.Row.Cells[0].Value.ToString();
            string objectType = e.Row.Cells[1].Value.ToString();
            List<AppObject> appObjects = null;
            using (CRMDataContext dataContext = new CRMDataContext())
            {
                appObjects = dataContext.AppObjects.Where(obj => (obj.Name == name && obj.ObjectType == objectType)).ToList();
                if (appObjects.Count > 0)
                {
                    dataContext.AppObjects.DeleteOnSubmit(appObjects[0]);
                    dataContext.SubmitChanges();

                    if (objectType == "TABLE")
                    {
                        Server srv = new Server("(local)");
                        Database db = srv.Databases["FlexiCRM"];
                        Table existingTable = db.Tables[name];
                        if (existingTable != null)
                        {
                            existingTable.Drop();
                        }
                    }
                }
            }
        }
    }
}
